package server;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SocketThread implements Runnable {
    private Socket socket;
    private static String header = "HTTP/1.1 200 OK\r\n" +
            "Content-Type: text/html;charSet=utf-8\r\n" +
            "\r\n";

    public SocketThread(Socket socket) {
        this.socket = socket;
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
            //从socket中，得到读取流，用于接收客服端发送的数据
            InputStream in = socket.getInputStream();
            //从socket中，得到写入流，用于将数据发送到客服端
            OutputStream out = socket.getOutputStream();
            //将写入流封装成response
            Response response = new Response(out);
            Request request=new Request(in);
            System.out.println(request);
            //将数据发送给客户端
            out.write(header.getBytes());
//                out.write("欢迎光临".getBytes());
            String url= request.getUrl();
            response.sendFile(url);


            //刷新流
            out.flush();
            //关闭流
            in.close();
            out.close();
            socket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
